<template>
	<!-- 健康视频 -->
	<view class="healthVideo-main">
		<!--  #ifndef  APP || H5 || WEB -->
		<view class="video-change" :style="dynamicStyle">
			<view class="video-changeList">
				<view class="video-changeList-item" @click.native="goToPath('/pages/healthVideo/healthVideo')">
					<view class="active title">推荐</view>
				</view>
				<view class="video-changeList-item" @click.native="goToPath('/pages/searchVideo/searchVideo')">
					<view class="title">发现</view>
				</view>
				<view class="video-changeList-item" @click.native="goToPath('/pages/searchVideo/searchVideo')">
					<view class="title">搜索</view>
				</view>
			</view>
		</view>
		<!-- #endif -->

		<!-- #ifndef  MP-WEIXIN-->
		<view class="video-change" :style="dynamicStyle">
			<view class="video-changeList">
				<view class="video-changeList-item" @click.native="goToPath('/pages/healthVideo/healthVideo')">
					<view class="active title">推荐</view>
				</view>
				<view class="video-changeList-item" @click.native="goToPath('/pages/searchVideo/searchVideo')">
					<view class="title">发现</view>
				</view>
				<view class="video-changeList-item" @click.native="goToPath('/pages/searchVideo/searchVideo')">
					<view class="title">搜索</view>
				</view>
			</view>
		</view>
		<!-- #endif -->

		<view class="uni-padding-wrap">
			<view class="page-section swiper">
				<view class="page-section-spacing">
					<swiper class="swiper" @change="changefun" @animationfinish="animationfinishfun" :current="index_" :vertical="true">
						<swiper-item v-for="(item, index) in videoList" :key="index">
							<view class="swiper-item" @click.stop="playPause(index)">
								<!-- 播放or暂停 -->
								<!-- <u-icon name="play-circle" color="#fff" size="60" v-if="!isPlay" class="btn play"></u-icon>
								<u-icon name="pause-circle" color="#fff" size="60" v-if="isPlay && firstclick" class="btn pause"></u-icon> -->
								<video
									loop="true"
									class="video"
									:id="'id' + index"
									:duration="item.duration"
									:enable-progress-gesture="true"
									:controls="false"
									:src="item.vlogUrl"
									:show-center-play-btn="false"
									object-fit="fill"
									:direction="0"
								>
									<!-- @timeupdate="(e) => videoUpdate(e, item, index)" -->
									<!-- 视频操作 -->
									<view class="video-option">
										<view class="option-item">
											<image
												src="https://test-zyxx-img.oss-cn-shenzhen.aliyuncs.com/uploads/20241202/0687e14dc77ff4a9686b9deb6615a5d3.png"
												style="height: 90rpx; width: 90rpx; border-radius: 50%"
											></image>
										</view>

										<!-- 点赞 -->
										<view class="option-item" @click.stop="getGiveLike(item.contentId, item.is_love)">
											<view style="margin-bottom: 45rpx">
												<uni-icons type="heart-filled" size="30" :color="item.is_love ? 'red' : '#fff'"></uni-icons>
											</view>
											<view style="font-size: 26rpx">{{ formatAmount(item.like) }}</view>
										</view>

										<!-- 评论 -->
										<view class="option-item" @click="openVideoComment(item.contentId)">
											<view style="margin-bottom: 45rpx">
												<uni-icons type="chat-filled" size="30" color="#fff"></uni-icons>
											</view>
											<view style="font-size: 26rpx">{{ formatAmount(item.commentNum) || '0' }}</view>
										</view>

										<!-- 关注 -->
										<view class="option-item" @click.stop="getFollow(item.contentId, item.is_collect)" style="height: 80rpx">
											<uni-icons type="star-filled" size="30" :color="item.is_collect ? '#ffcb00' : '#fff'"></uni-icons>
										</view>

										<!-- 分享 -->
										<view class="option-item" @click.stop="getShare(item)" style="height: 140rpx">
											<button open-type="share" class="shareBtn">
												<uni-icons type="redo-filled" size="30" color="#fff"></uni-icons>
												<text style="font-size: 24rpx;color: #fff;">微信分享</text>
											</button>
										</view>
									</view>

									<!-- 视频详情 -->
									<view class="video-info">
										<view class="info-time">
											{{ formatTimestamp(item.createtime) }}
										</view>
										<view class="infos">
											{{ item.desc }}
										</view>
									</view>
								</video>
							</view>
						</swiper-item>
					</swiper>
				</view>
			</view>
		</view>

		<u-popup :show="show" @close="getClose" :round="10" mode="bottom" closeable>
			<view class="videoComment">
				<view class="videoComment-header">评论内容({{ videoCommentList.length }})</view>

				<view class="videoComment-content">
					<view class="videoComment-item" v-for="(item, index) in videoCommentList" :key="index">
						<view class="userImgae">
							<image :src="imageUrl(item.user.avatar)" mode="widthFix" style="width: 80rpx; height: 80rpx; border-radius: 50%"></image>
						</view>
						<view class="userInfo">
							<view class="userName">
								{{ item.user.nickname }}
							</view>
							<view class="userComment">
								{{ item.content }}
							</view>
						</view>
					</view>
				</view>

				<view class="videoComment-push" :style="bottomStyle">
					<u--input placeholder="请输入内容" border="surround" v-model="commentValue"></u--input>
					<text class="push" @click="getVideoCommentPush">发布</text>
				</view>
			</view>
		</u-popup>
		
		<hwxcTabbar/>
	</view>
</template>

<script>
import { videoList, videoComment, videoCommentPush, videocollect, videolove } from '../../api/video/index.js';
import hwxcTabbar from '../../components/hwxcTabbar.vue';
import {  formatAmountWk } from '../../utils/tools.js';
export default {
	data() {
		return {
			videoList: [],
			index_: null,
			index: '0',
			firstclick: false,
			is_active: true,
			isPlay: true,
			activeObj: null,
			sending: false,
			contentId: '',
			updateState: true,
			videoContext: null,

			topNum: 0,
			show: false,
			videoCommentList: [],
			commentValue: '',
			videoId: ''
		};
	},
	
	components:{
		hwxcTabbar
	},

	onShareAppMessage() {
		return {
			title: '健康视频',
			path: 'pages/healthVideo/healthVideo'
		};
	},
	
	onShareTimeline() {
		return {
			title: '健康视频',
			query: 'pages/healthVideo/healthVideo'
		};
	},

	computed: {
		dynamicStyle() {
			return `top:${this.topNum ? this.topNum : 60}rpx`;
		},
		bottomStyle() {
			const systemInfo = uni.getSystemInfoSync();
			const { safeAreaInsets } = systemInfo;
			const bottomSafeAreaHeight = safeAreaInsets.bottom || 0;
			return `padding-bottom: ${bottomSafeAreaHeight ? bottomSafeAreaHeight + 'px' : '30rpx'}`;
		}
	},

	async onShow() {
		const capsulePosition = await this.getCapsulePosition();
		this.topNum = capsulePosition.top;
	},

	onLoad(option) {
		this.oprateVideoList();
		// 初始化第一个视频 并播放
		this.$nextTick(function () {
			let videoContext = uni.createVideoContext(`id0`);
			videoContext.play();
		});
		
		// 通过 id 获取 nvue 子窗体  
		const subNVue = uni.getSubNVueById('videoOption');
		
		// 打开 nvue 子窗体  
		subNVue.show(); 
		
	},
	watch: {
		index_(val) {
			this.videoContext = uni.createVideoContext(`id${this.index_}`);
			this.contentId = this.videoList[val]['contentId'];
		},
		activeObj(val, oldval) {
			if (!oldval) {
				this.$nextTick(function () {
					let videoContext = uni.createVideoContext(`id${this.index_}`);
					videoContext.play();
				});
			}
		}
	},
	methods: {
		// current 改变时会触发 change 事件，event.detail = {current: current, source: source}
		// 暂停当前的视频播放
		async changefun(e) {
			const { current, source } = e.detail;
			// 获取视频评论
			const commentData = await videoComment({
				id: this.videoList[current].contentId
			});
			this.videoList[current].commentNum = commentData.data.length;

			this.is_active = false;
			let videoContext = uni.createVideoContext('id' + this.index_);
			videoContext.pause();
		},

		// 跳转
		goToPath(path) {
			console.log(path);
			uni.navigateTo({
				url: path
			});
		},
		
		formatAmount(num) {
			return formatAmountWk(num);
		},

		playPause(current) {
			// 点击视频时  如果播放就暂停 如果是暂停就开始播放
			let videoContext = uni.createVideoContext('id' + current);
			this.firstclick = true;
			if (this.isPlay) {
				videoContext.pause();
				this.isPlay = false;
			} else {
				videoContext.play();
				this.isPlay = true;
			}
		},

		// 	动画结束时会触发 animationfinish 事件，event.detail = {current: current, source: source}
		animationfinishfun(e) {
			let that = this;
			this.isPlay = true;
			// 获取下标
			let current = e.detail.current;
			this.activeObj = this.videoList[current];
			this.index_ = current;
			this.is_active = true;
			this.videoList[current]['istrue'] = true;
			// 获取当前的 video 标签 并暂停播放
			let videoContext = uni.createVideoContext('id' + this.index_);
			videoContext.pause();
			// 初始化新的video 并播放
			videoContext = uni.createVideoContext('id' + current);
			videoContext.play();
			//  视频滑到最后一个 就再去请求新的 视频列表
			if (this.videoList.length > 0 && current + 1 == this.videoList.length && !this.sending) {
				this.oprateVideoList(this.videoList[current]['contentId']);
			}
		},

		// 进度条计算
		videoUpdate(e, item, index) {
			// 此处用来计算进度条
			if (this.updateState) {
				// #ifdef MP-WEIXIN
				if (e.target.id == 'id' + index) {
					this.videoList[this.index_]['currentTime'] = (e.detail.currentTime / e.detail.duration) * 100;
					this.videoList[this.index_]['duration'] = e.detail.duration;
				}
				// #endif
				// #ifdef MP-ALIPAY
				this.videoList[this.index_]['currentTime'] = (e.detail.currentTime / e.detail.videoDuration) * 100;
				this.videoList[this.index_]['duration'] = e.detail.videoDuration;
				// #endif
			}
		},

		// 拖动过程中触发的事件，event.detail = {value: value}
		sliderChanging(e) {
			this.updateState = false;
		},

		//拖动进度条触发事件
		sliderChange(e) {
			let duration = this.videoList[this.index_]['duration'];
			if (duration) {
				this.videoContext.seek((e.detail.value / 100) * duration); //完成拖动后，计算对应时间并跳转到指定位置
				this.videoList[this.index_]['duration'] = e.detail.value;
				this.updateState = true;
			}
		},

		// 获取视频列表
		async oprateVideoList(id) {
			this.sending = true;
			const resData = await videoList();
			const infoObjs = this.$store.state.commInitInfo;
			const resp = [];
			if (resData && resData.data.length > 0) {
				const videoList = resData.data;
				// 获取视频评论
				const commentData = await videoComment({
					id: videoList[0].id
				});
				videoList.forEach((item) => {
					resp.push({
						contentId: item.id,
						vlogUrl: infoObjs.uploaddata.cdnurl + item.url,
						title: item.title,
						desc: item.desc,
						like: item.like,
						createtime: item.createtime,
						is_love: item.is_love,
						is_collect: item.is_collect
					});
				});
				resp[0].commentNum = commentData.data.length;
			}

			resp.map((res) => {
				res['istrue'] = false;
				res['currentTime'] = 0;
				res['duration'] = 0;
			});
			this.videoList = resp;
		},

		// 点赞
		async getGiveLike(id, is_love) {
			try {
				const resData = await videolove({
					id
				});
				if (resData.code == 1) {
					if (!is_love) {
						this.videoList.forEach((item) => {
							if (item.contentId == id) {
								item.like++;
								item.is_love = true;
							}
						});
					} else {
						this.videoList.forEach((item) => {
							if (item.contentId == id) {
								item.like--;
								item.is_love = false;
							}
						});
					}
				} else {
					uni.showToast({
						title: resData.msg,
						icon: 'none'
					});
				}
			} catch (e) {
				throw Error(e);
			}
		},

		// 关注
		async getFollow(id, is_collect) {
			try {
				const resData = await videocollect({
					id
				});
				if (resData.code == 1) {
					if (!is_collect) {
						this.videoList.forEach((item) => {
							if (item.contentId == id) {
								item.is_collect = true;
							}
						});
					} else {
						this.videoList.forEach((item) => {
							if (item.contentId == id) {
								item.is_collect = false;
							}
						});
					}
				} else {
					uni.showToast({
						title: resData.msg,
						icon: 'none'
					});
				}
			} catch (e) {
				throw Error(e);
			}
		},

		// 分享
		getShare(videoInfo) {
			// 通用的分享逻辑
			const title = videoInfo.name;
			const description = videoInfo.desc;

			if (uni.getSystemInfo().platform === 'android' || uni.getSystemInfo().platform === 'ios') {
				// App 端分享
				this.shareApp(title, description, imageUrl);
			} else {
				// 小程序端分享
				uni.showShareMenu({
					title,
					withShareTicket: true
				});
			}
		},

		// app分享
		shareApp(title, description, imageUrl) {
			uni.share({
				provider: 'weixin',
				scene: 'WXSceneSession',
				type: 0,
				href: '',
				title: title,
				content: description,
				imageUrl: imageUrl
			});
		},

		// 顶部胶囊位置
		getCapsulePosition() {
			return new Promise((resolve, reject) => {
				uni.getSystemInfo({
					success: (res) => {
						const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
						const statusBarHeight = res.statusBarHeight;
						const navigationBarHeight = menuButtonInfo.top + menuButtonInfo.height - statusBarHeight;
						resolve({
							width: menuButtonInfo.width,
							height: menuButtonInfo.height,
							top: menuButtonInfo.top + statusBarHeight,
							right: res.windowWidth - menuButtonInfo.right,
							bottom: menuButtonInfo.top + menuButtonInfo.height + statusBarHeight,
							left: res.windowWidth - menuButtonInfo.right - menuButtonInfo.width
						});
					},
					fail: (err) => {
						reject(err);
					}
				});
			});
		},

		// 打开评论
		async openVideoComment(id) {
			console.log(id);
			this.show = true;
			this.videoId = id;
			this.commentValue = '';
			const resData = await videoComment({
				id
			});
			this.videoCommentList = resData.data;
		},

		// 关闭评论
		getClose() {
			this.show = false;
		},

		imageUrl(fileUrl) {
			if (fileUrl.indexOf('data:image') > -1) {
				return fileUrl;
			} else {
				const cdnurl = this.$store.state.commInitInfo.uploaddata.cdnurl;
				return cdnurl + fileUrl;
			}
		},

		// 发布评论
		async getVideoCommentPush() {
			if (!this.commentValue) {
				return uni.showToast({
					title: '请输入内容',
					icon: 'none'
				});
			}

			const resData = await videoCommentPush({
				id: this.videoId,
				content: this.commentValue
			});
			if (resData.code == 1) {
				uni.showToast({
					title: '发布成功',
					icon: 'none'
				});
				setTimeout(() => {
					this.openVideoComment(this.videoId);
					this.videoList.forEach((item) => {
						if ((item.contentId = this.videoId)) {
							item.commentNum++;
						}
					});
				}, 500);
			} else {
				uni.showToast({
					title: '发布失败',
					icon: 'none'
				});
			}
		},

		// 时间格式化
		formatTimestamp(timestamp) {
			// 将时间戳转换为Date对象
			const date = new Date(timestamp * 1000);
			// 获取年份
			const year = date.getFullYear();
			// 获取月份，注意getMonth方法返回值是从0开始计数的，所以要加1
			const month = (date.getMonth() + 1).toString().padStart(2, '0');
			// 获取日期并格式化为两位数
			const day = date.getDate().toString().padStart(2, '0');
			// 获取小时数并格式化为两位数
			const hours = date.getHours().toString().padStart(2, '0');
			// 获取分钟数并格式化为两位数
			const minutes = date.getMinutes().toString().padStart(2, '0');
			// 获取秒钟数并格式化为两位数
			const seconds = date.getSeconds().toString().padStart(2, '0');
			// 拼接成格式化后的时间字符串
			const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			return formattedTime;
		}
	}
};
</script>

<style scoped lang="scss">
.swiper {
	height: 100vh;
	position: relative;
	.slider {
		height: 20rpx;
		position: absolute;
		bottom: 67rpx;
		left: 0;
		width: 750rpx;
		slider {
			margin: 0;
		}
	}

	.swiper-item {
		height: 100vh;
		position: relative;
		.btn {
			position: absolute;
			width: 120rpx;
			height: 120rpx;
			background: none;
			z-index: 2;
			top: 50%;
			margin-top: -60rpx;
			left: 50%;
			margin-left: -60rpx;
			&.pause {
				animation: benone 0.2s 2s linear forwards;
			}
		}
	}
}

.video {
	width: 100%;
	height: 100vh;
	position: relative;
}

::v-deep .uni-video-container {
	background-color: #fff !important;
}

.left_box {
	position: fixed;
	bottom: 55px;
	left: 0rpx;
	width: 100%;
	height: 600rpx;
	pointer-events: none;
	z-index: 8;
	background: linear-gradient(to bottom, rgba(0, 0, 0, 0), rgba(0, 0, 0, 1));

	.slider {
		pointer-events: initial;
		height: 20rpx;
		position: absolute;
		bottom: 67rpx;
		left: 0;
		width: 750rpx;

		slider {
			margin: 0;
		}
	}

	::v-deep .u-icon {
		position: fixed;
		right: 40rpx;
		bottom: 280rpx;
		pointer-events: initial;
		z-index: 10;
	}
}

@keyframes benone {
	from {
		opacity: 1;
	}

	to {
		opacity: 0;
	}
}

.video-info {
	position: absolute;
	bottom: 90rpx;
	left: 30rpx;
	color: #fff;
	width: 500rpx;
	font-size: 28rpx;
	z-index: 999;

	.info-time {
		color: #d9d9d9;
		margin-bottom: 20rpx;
	}

	.infos {
		font-size: 30rpx;
		line-height: 1.5;
	}
}

.video-change {
	display: flex;
	justify-content: center;
	align-items: center;
	position: fixed;
	left: 0px;
	width: 100%;
	color: #fff;
	height: 120rpx;
	font-size: 28rpx;
	height: 80rpx;
	z-index: 9999;
	.video-changeList {
		display: flex;
		align-items: center;
		justify-content: center;
		.video-changeList-item {
			width: 120rpx;
			text-align: center;
			.active {
				border-bottom: 3px #fff solid;
			}
			.title {
				display: inline-block;
				margin-bottom: 10rpx;
			}
		}
	}
}

.video-option {
	display: flex;
	flex-direction: column;
	width: 120rpx;
	position: absolute;
	right: 20rpx;
	bottom: 100rpx;
	z-index: 999;
	.option-item {
		height: 140rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #fff;
	}
}

.tabberBox {
	width: 100%;
	background-color: #fff;
	position: fixed;
	left: 0;
	bottom: 0px;
	height: 50px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	.tableItem {
		width: 25%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		.tabber-image {
			margin-bottom: 5px;
			.images {
				width: 24px;
				height: 24px;
			}
		}

		.tabber-title {
			font-size: 12px;
		}
	}
}

.videoComment {
	box-sizing: border-box;
	padding: 30rpx;
	position: relative;
	.videoComment-header {
		font-size: 28rpx;
		color: #444;
		font-weight: bold;
		margin-bottom: 30rpx;
	}
	.videoComment-content {
		height: 50vh;
		overflow-y: scroll;
		padding-bottom: 50rpx;
		.videoComment-item {
			display: flex;
			align-items: flex-start;
			margin-bottom: 50rpx;
			font-size: 26rpx;
			.userImgae {
				width: 100rpx;
			}
			.userInfo {
				flex: 1;
				.userName {
					margin-bottom: 8rpx;
					color: #999;
				}

				.userComment {
					color: #444;
				}
			}
		}
	}
	.videoComment-push {
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: absolute;
		bottom: 0px;
		left: 0px;
		width: 100%;
		box-sizing: border-box;
		padding: 30rpx;
		padding-bottom: 0px;
		background-color: #fff;
		.push {
			width: 70rpx;
			line-height: 70rpx;
			display: inline-block;
			text-align: center;
			font-size: 26rpx;
			margin-left: 20rpx;
			background-color: #e43927;
			width: 120rpx;
			color: #fff;
			border-radius: 6rpx;
		}
	}
}

.shareBtn {
	padding: 0px;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	background-color: transparent;
	line-height: normal;
	font-size: 28rpx;
}

button:after {
	border: none !important;
}
</style>
